package com.bree.erp.service.stateless;

import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.bree.erp.entity.MovementType;
import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.Project;
import com.bree.erp.entity.Returns;
import com.bree.erp.entity.User;
import com.bree.erp.entity.Warehouse;
import com.bree.erp.service.ReturnsBalanceService;
import com.bree.erp.service.ReturnsService;

@Stateless
public class ReturnsServiceBean implements ReturnsService {

	@PersistenceContext()
	private EntityManager em;
	
	
	public ReturnsServiceBean() {
		
	}
	
	public ReturnsServiceBean(EntityManager em, ReturnsBalanceService balanceService) {
		this.em = em;
	}

	@Override
	public Returns create(Date entryDate, Long projectId, String warehouseId,
			Long partUnitId, double quantity, String location, String userId) {
		
		Project project = em.find(Project.class, projectId);
		Warehouse warehouse = em.find(Warehouse.class, warehouseId);
		PartUnit partUnit = em.find(PartUnit.class, partUnitId);
		User user = em.find(User.class, userId);
		
		return create(entryDate, project, warehouse, partUnit, quantity, location, user);
	}
	
	@Override
	public Returns create(Date entryDate, Project project, Warehouse warehouse,
			PartUnit partUnit, double quantity, String location, User user) {
		
		Returns entity = new Returns();
		
		entity.setEntryDate(entryDate);
		entity.setProject(project);
		
		if(warehouse == null && project != null) {
			entity.setWarehouse(project.getDefaultWarehouse());
		} else {
			entity.setWarehouse(warehouse);
		}
		
		entity.setPartUnit(partUnit);
		entity.setQuantity(quantity);
		entity.setLocation(location);
		
		entity.setMovementType(MovementType.IN);
		
		entity.setCreatedBy(user);
		entity.setCreated(new Date());
		
		em.persist(entity);
		
		return entity;
	}

	@Override
	public Returns read(Long id) {
		
		return em.find(Returns.class, id);
	}

	@Override
	public Returns update(Long id, Date entryDate, double quantity,
			String location, String remarks, String userId) {
		
		Returns entity = read(id);
		
		entity.setEntryDate(entryDate);
		entity.setQuantity(quantity);
		entity.setLocation(location);
		entity.setRemarks(remarks);
		
		User user = em.find(User.class, userId);
		entity.setUpdatedBy(user);
		entity.setUpdated(new Date());
		
		return entity;
	}

	@Override
	public void delete(Long id) {

		Returns entity = read(id);
			
		em.remove(entity);
	}

}
